import Vue from "vue";
import Vuex from "vuex";
import routerModule from "./router";
import createPersistedState from "vuex-persistedstate";
console.log("routerModule====>", routerModule);

Vue.use(Vuex);
const state = {
  count: 0,
  mutationData: "testtest",
  products: [
    { name: "鼠标", price: 20 },
    { name: "键盘", price: 40 },
    { name: "耳机", price: 60 },
    { name: "显示屏", price: 80 },
  ],
};
const getters = {
  saleProducts: (state) => {
    let saleProducts = state.products.map((product) => {
      return {
        name: product.name,
        price: product.price / 2,
      };
    });
    return saleProducts;
  },
};
const mutations = {
  increment(state) {
    state.count++;
  },
  mutationTest(state, data) {
    state.mutationData = data;
  },
  minusPrice(state, payload) {
    console.log("minusPrice====>", state, payload);
    state.products.forEach((product) => {
      product.price -= payload;
    });
  },
};
const actions = {
  //和mutations对应
  minusPriceAsync(context, data) {
    setTimeout(() => {
      context.commit("minusPrice", data); //context提交
    }, 2000);
  },
  routesInfo({ state }) {
    let routes = {
      children: this.$router.options.routes,
    };
    let route = this.$route.matched;
    for (let i = 0; i < route.length - 1; i++) {
      routes = routes.children.find((e) => e.name == route[i].name);
    }
    console.log("routes===vuex==", routes);
    state.routes = routes.children;
  },
};

//定义需要保存的数据,某个数据的定义方法
/*  const persiste = createPersistedState({
  paths: ['mutationData']
})  */
const persiste = createPersistedState({
  paths: ["routerModule.allRoutes", "routerModule.routesKeyAndName"],
});
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
    routerModule: routerModule,
  },
  plugins: [persiste],
  /*    createPersistedState({
      // storage: window.sessionStorage
    }) */
  //缓存所有store数据到本地 也可以单独缓存 https://www.jianshu.com/p/ce13051d1124
});
